import { useState, useEffect, useRef, useMemo } from 'react';
import { Table, Form, MF } from 'com';
import menuStore from 'store/menu';
import { SearchFee, AddFee } from 'api/students';
import { getStudentFee } from 'api/dictionary';
import { confirm } from '@/utils/common';
import dayjs from 'dayjs';

/**
 * 列
 */
const cols = [
    {
        title: '学生姓名',
        dataIndex: 'student_name',
        align: 'center'
    },
    {
        title: '费用',
        dataIndex: 'fee',
        align: 'center'
    },
    {
        title: '缴费类型',
        dataIndex: 'type_name',
        align: 'center'
    },
    {
        title: '缴费日期',
        dataIndex: 'date',
        align: 'center',
        render: text => dayjs(text).format('YYYY-MM-DD')
    }
]

export default () => {
    /**
        * 列表
        */
    const [list, setList] = useState([]);
    /**
     * loading
     */
    const [loading, setLoading] = useState(false);
    /**
     * 总条数
     */
    const [total, setTotal] = useState(0);
    /**
     * 缴费类型
     */
    const [types, setTypes] = useState([{ label: '所有', value: 0 }]);
    /**
     * 添加MF引用
     */
    const addMF = useRef();
    /**
     * 添加表单配置项
     */
    const addOptions = useMemo(() => {
        const [a, ...rest] = types;
        return {
            student_id: {
                title: '学生',
                tag: 'ss',
                required: true
            },
            fee: {
                title: '费用',
                required: true,
                style: { width: '100%' },
                tag: 'number',
                attrs: { min: 1 }
            },
            date: {
                title: '日期',
                tag: 'date',
                required: true,
            },
            type: {
                title: '缴费类型',
                tag: 'select',
                required: true,
                values: rest
            }
        }
    }, [types]);
    /**
     * 搜索表单配置项
     */
    const options = useMemo(() => ({
        ...(menuStore.auth('searchFee') && {
            student_id: {
                title: '学生',
                tag: 'ss',
                clear: true
            },
            min_fee: {
                title: '最低费用',
                tag: 'number',
                attrs: { min: 1 }
            },
            max_fee: {
                title: '最高费用',
                tag: 'number',
                attrs: { min: 2 }
            },
            start_date: {
                title: '开始日期',
                tag: 'date'
            },
            end_date: {
                title: '结束日期',
                tag: 'date'
            },
            type: {
                title: '缴费类型',
                tag: 'select',
                style: { width: 110 },
                values: types
            },
            search: {
                tag: 'button',
                text: '搜索',
                htmlType: 'submit',
                type: 'primary'
            }
        }),
        ...(menuStore.auth('addFee') && {
            add: {
                tag: 'button',
                text: '添加',
                type: 'primary',
                click: () => addMF.current.show()
            }
        })
    }), [types]);

    /**
     * 搜索模型
     */
    const [searchModel, setSearchModel] = useState({
        pageNo: 1,
        pageSize: 10,
        type: 0
    });

    menuStore.auth('searchFee') && useEffect(() => {
        (async () => {
            setLoading(true);
            try {
                const obj = { ...searchModel };
                if (obj.start_date) {
                    obj.start_date = dayjs(obj.start_date).format('YYYY-MM-DD');
                }
                if (obj.end_date) {
                    obj.end_date = dayjs(obj.end_date).add(1, 'day').format('YYYY-MM-DD');
                }
                const { data, total } = await SearchFee(obj);
                setList(data);
                setTotal(total);
            } catch (error) { }
            setLoading(false);
        })()
    }, [searchModel]);

    menuStore.auth('searchFee') && useEffect(() => {
        (async () => {
            try {
                const list = await getStudentFee();
                setTypes([...types, ...list.map(c => ({ label: c.name, value: c.id }))]);
            } catch (error) { }
        })()
    }, []);

    /**
     * 添加费用
     * @param {*} values 
     */
    const addFee = async values => {
        try {
            await confirm('数据一旦保存将无法修改和删除，请仔细检查，您确定要继续保存吗？');
            addMF.current.start();
            await AddFee({ ...values, date: dayjs(values.date).format('YYYY-MM-DD') });
            addMF.current.hide();
            setSearchModel({ ...searchModel });
        } catch (error) { }
        addMF.current.stop();
    }

    return <div>
        <h3>学生费用管理</h3>
        <hr />
        {menuStore.auth('searchFee', 'addFee') && <Form options={options} values={searchModel} attrs={{ layout: "inline" }} onFinish={v => setSearchModel({ ...searchModel, ...v, pageNo: 1 })} />}
        <p></p>
        {menuStore.auth('searchFee') && <Table cols={cols} data={list} loading={loading} total={total} page={searchModel} onChange={setSearchModel} />}
        {menuStore.auth('addFee') && <MF onFinish={addFee} options={addOptions} title="添加费用" ref={addMF} lw={80} />}
    </div>
}